const express = require("express");
let router = express.Router();
const DB = require("../utils/db完整.js");
const { api_url } = require("../config/config.js")

router.get("/searchlist", async (req, res, next) => {
    //searchtext必填
    console.log('被请求了');
    let { page = 1, size = 6, searchtext } = req.query;
    if (!searchtext) {
        return;
    }
    let sql = `select id,cid,title,price,
    concat("${api_url}","/uploads/","online/",image_src) as image_src,
    type_name,
    area_name,
    subject_name,
    grade_name
    from e_course  
    where 
    title like "%${searchtext}%" or 
    grade_name like "%${searchtext}%" or 
    subject_name like "%${searchtext}%" or 
    area_name like "%${searchtext}%" or 
    category_name like "%${searchtext}%"`;
    let [err, result] = await DB(sql);
    if (err) {
        next("总条数请求失败");
        return;
    };
    console.log(err,'搜索错误');
    console.log(result.length,'搜索结果');
    // console.log(size);
    // console.log(result.length);
    let row = result.length;
    let pages = Math.ceil(row / size);
    let dataAll=result;
    // console.log(row);
    // console.log(pages);
    let sql2 = `select id,cid,title,price,
    concat("${api_url}","/uploads/","online/",image_src) as image_src,
    type_name,
    area_name,
    subject_name,
    grade_name
    from e_course 
    where title like "%${searchtext}%" or 
    grade_name like "%${searchtext}%" or 
    subject_name like "%${searchtext}%" or
    area_name like "%${searchtext}%" or  
    category_name like "%${searchtext}%" 
    limit ${size * (page - 1)},${size}`;

    let [err1, result1] = await DB(sql2);
    console.log(err1,'搜索错误1');
    console.log(result1.length,'搜索结果1');
    if (err1) {
        next("请求失败");
        return
    }
    res.send({
        status: 200,
        msg: "请求成功",
        result: {
            data: result1,
            page: Number(page),
            pages,
            row,
            dataAll
        }
    })
})





module.exports = router;